import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {filter, map} from 'rxjs/operators';
import {ErrRes} from 'src/app/frame/global/err-res';
import {AftApplyOrder, AftApplyOrderCondition} from '../../aft-apply-order.type';
import {UrlRou} from 'src/app/frame';
import {isNullOrUndefined} from 'util';
import {Services} from 'src/app/frame/module/services';
import {AftApplyOrderLine} from '../../../aft-apply-order-line/aft-apply-order-line.type';
import {Zero3Enum} from '../../../../../frame/enum/zero3-enum';

@Component({
    selector: 'app-main-refund-aft-apply-order',
    templateUrl: './main-refund-aft-apply-order.component.html',
    styleUrls: ['./main-refund-aft-apply-order.component.css']
})
export class MainRefundAftApplyOrderComponent implements OnInit {

    errRes = new ErrRes();
    zero3Enums = Zero3Enum;
    domain: AftApplyOrder = new AftApplyOrder();
    aftApplyOrderLineDomain: AftApplyOrderLine = new AftApplyOrderLine();

    extend = {
        domain: {
            serAudit: {
                nickname: ''
            },
        },
    };

    func = {
        loadDomain: (uuid: string) => {
            const condition: AftApplyOrderCondition = new AftApplyOrderCondition();
            condition.uuid = uuid;
            Services.aftApplyOrder.info(condition)
                .pipe(filter(item => item.code === 'success' && !isNullOrUndefined(item.domain)))
                .pipe(map(item => item.domain))
                .subscribe(domain => {
                    this.domain = domain;
                    this.func.loadAftApplyOrderLineDomain(uuid);
                });
        },

        loadAftApplyOrderLineDomain: (serAfterSaleId: string) => {
            Services.aftApplyOrderLine.find_by_ser_after_sale_id(serAfterSaleId)
                .pipe(filter(item => item.code === 'success' && !isNullOrUndefined(item.domains)))
                .pipe(map(item => item.domains[0]))
                .subscribe(domain => {
                    this.aftApplyOrderLineDomain = domain;
                });
        },

        update: {
            req: (event) => {
                Services.aftApplyOrder.update(this.domain, this.func.update.callback).subscribe();
            },
            callback: {
                success: (result) => {
                    this.router.navigate([UrlRou.aftApplyOrder.list]);
                },
                error: (result) => {
                    this.errRes.error = result.error;
                    this.errRes.statusText = result.statusText;
                }
            }
        }
    };

    constructor(private route: ActivatedRoute,
                private router: Router) {
    }

    ngOnInit() {
        const uuid = this.route.snapshot.paramMap.get('uuid');
        this.func.loadDomain(uuid);

    }

}
